<template>
    <div ref="chartRef" style="width: 98vw;padding-left: 2rem; height: 300px;"></div>
</template>

<script setup lang="ts">
import { nextTick, ref, onMounted, watch, defineProps } from 'vue';
import * as echarts from 'echarts';
import { getWant } from "@/api/index";

const xValue = ref<string[]>([]);
const yValue = ref<number[]>([]);

const chartRef = ref<HTMLElement | null>(null); 4

// const { want } = defineProps(['want'])

// xValue.value = want.map(item => item.xValue);
// yValue.value = want.map(item => item.yValue);

// 获取数据
getWant().then(res => {
    // console.log(res.data.data.trendData.wantChart.series[0].data);
    const result = res.data.data.trendData.wantChart.series[0].data;
    xValue.value = result.map(item => item.xValue);
    yValue.value = result.map(item => item.yValue);
});

const option = ref({
    xAxis: {
        type: 'category',
        data: xValue.value
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            data: yValue.value,
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#FFA500' // 设置线条颜色为橘色
            },
            itemStyle: {
                color: '#FFA500' // 设置点的颜色为橘色
            }
        }
    ]
});

// 更新图表
function updateChart() {
    if (chartRef.value !== null) {
        const myChart = echarts.getInstanceByDom(chartRef.value);
        if (myChart) {
            myChart.dispose();
        }

        const newChart = echarts.init(chartRef.value);
        newChart.setOption(option.value);
    }
}

// 监视 xValue 和 yValue 的变化，并在数据更新后重新渲染图表
watch([xValue, yValue], () => {
    if (xValue.value.length && yValue.value.length) {
        option.value = {
            xAxis: {
                type: 'category',
                data: xValue.value
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: yValue.value,
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        color: '#FFA500' // 设置线条颜色为橘色
                    },
                    itemStyle: {
                        color: '#FFA500' // 设置点的颜色为橘色
                    }
                }
            ]
        };

        // 数据更新后重绘图表
        updateChart();
    }
}, { immediate: true });

onMounted(() => {
    // 初始图表渲染
    if (chartRef.value !== null) {
        const myChart = echarts.init(chartRef.value);
        myChart.setOption(option.value);
    }
});
</script>

<style scoped></style>